import path from "@/framework/util/path.ts";

/**
 * .npmrc文件操作
 */
export class NpmrcFile {
  readonly filePath: string;
  private readonly _backupFile: string;
  private _values: Record<string, string> = {};

  constructor(filePath?: string) {
    this.filePath = filePath || path.join(native.process.env.USERPROFILE!, ".npmrc");
    this._backupFile = this.filePath + ".bak";
  }

  async load(): Promise<void> {
    try {
      this._values = {};
      const content = await native.fs.readFileText(this.filePath);
      if (content) {
        const lines = content.split("\n");
        for (let line of lines) {
          line = line.trim();
          if (line.length === 0 || line.startsWith(";") || line.startsWith("#")) {
            continue;
          }
          const [key, value] = line.split("=");
          this._values[key.toLowerCase()] = value;
        }
      }
      if (__DEV__) console.log("npmrc file loaded.", this);
    } catch (e: any) {
      console.error("npmrc file load error", e);
    }
  }

  async save() {
    try {
      await this.backup();
      const content = Object.entries(this._values)
        .map(([key, value]) => `${key}=${value}`)
        .join("\n");
      await native.fs.writeFile(this.filePath, content);
    } catch (e: any) {
      console.error(e);
    }
  }

  get = (key: string) => this._values[key.toLowerCase()];
  set = (key: string, value: string): void => void (this._values[key.toLowerCase()] = value);

  /** 备份文件 */
  async backup() {
    try {
      const exists = await native.fs.exists(this._backupFile);
      if (!exists) {
        await native.fs.copyFile(this.filePath, this._backupFile);
      }
    } catch (e: any) {
      console.error(e);
    }
  }
}
